import {
  ModalForm,
  ProForm,
  ProFormDatePicker,
  ProFormInstance,
  ProFormText,
  ProFormTextArea
} from '@ant-design/pro-components';
import { message } from 'antd';
import { useEffect, useRef } from 'react';
import { waitTime } from '@/utils/request';
import { addArticle, updateArticle } from '@/services/api/article';
import moment from "moment";

interface InputDialogProps {
  detailData?: API.ArticleDTO;
  visible: boolean;
  onClose: (result: boolean) => void;
}

export default function InputDialog(props: InputDialogProps) {
  const form = useRef<ProFormInstance>(null);

  useEffect(() => {
    waitTime().then(() => {
      if (props.detailData) {
        form?.current?.setFieldsValue(props.detailData);
      } else {
        form?.current?.resetFields();
      }
    });
  }, [props.detailData, props.visible]);

  const onFinish = async (values: any) => {
    const { title, author, content,publishTime } = values;
    const data: API.ArticleDTO = {
      id: props.detailData?.id,
      title,
      author,
      content,
      publishTime
    };
    if (props.detailData) {
      await updateArticle(data);
    } else {
      await addArticle(data);
    }
    message.success('保存成功');
    props.onClose(true);
    return true;
  };

  return (
    <ModalForm
      width={600}
      onFinish={onFinish}
      formRef={form}
      modalProps={{
        destroyOnClose: true,
        onCancel: () => props.onClose(false),
      }}
      title={props.detailData ? '修改文章' : '新建文章'}
      open={props.visible}
    >
      <ProFormText
        name="title"
        label="文章名称"
        rules={[
          {
            required: true,
            message: '请输入文章名称！',
          },
        ]}
      />
        <ProFormText
          name="author"
          label="作者"
          rules={[
            {
              required: true,
              message: '请输入作者！',
            },
          ]}
    />
      <ProFormDatePicker
        name="publishTime"
        label="发布日期"
        initialValue={moment()}
        rules={[
          {
            required: true,
            message: '请输入发布日期！',
          },
        ]}
      />
    <ProFormTextArea
      name="content"
      label="文章内容"
      rules={[
        {
          required: true,
          message: '请输入文章内容！',
        },
      ]}
    />
  </ModalForm>
  );
}
